package com.ms.pda.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.SoundPool
import android.net.Uri
import com.ms.pda.model.SoundKey
import java.io.IOException
import java.util.*
import java.util.concurrent.LinkedBlockingQueue
import kotlin.concurrent.timerTask

object SoundUtil {

    private val soundPool: SoundPool = SoundPool.Builder()
        .setMaxStreams(50)
        .setAudioAttributes(
            AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build()
        )
        .build()
    private val soundMap: Map<SoundKey, List<Int>> = mutableMapOf()
    private val blockQueue: LinkedBlockingQueue<List<Int>> = LinkedBlockingQueue()
    private var timer: Timer? = null
    private var timerTask: TimerTask? = null
    private var playingId: Int? = -1

    fun play(key: SoundKey) {
        if (soundMap.isEmpty()) {
            throw RuntimeException("音频资源未初始化")
        }
        if (!soundMap.containsKey(key)) {
            return
        }

        val sound = soundMap[key]
        blockQueue.put(sound)
        if (playingId == -1) {
            timerTask = timerTask {
                if (blockQueue.isNotEmpty()) {
                    val playSound = blockQueue.poll()
                    playingId = playSound?.get(0)
                    val duration = playSound?.get(1)
                    playingId?.let {
                        soundPool.play(it, 1f, 1f, 1, 0, 1f)
                    }
                    Thread.sleep(duration!!.plus(100).toLong())
                } else {
                    timerTask?.cancel()
                    timerTask = null
                    timer?.cancel()
                    timer = null
                    playingId = -1
                }
            }
            timer = Timer()
            timer!!.schedule(timerTask!!, 100, 100)
        }

    }

    fun loadResources(context: Context) {

    }

    /**
     * 加载音频文件
     */
    private fun loadRaw(context: Context, raw: Int): List<Int> {
        val soundId: Int = soundPool.load(context, raw, 1)
        val duration = getMp3Duration(context, raw)
        return listOf(soundId, duration)
    }

    /**
     * 获取音频文件的时长
     */
    private fun getMp3Duration(context: Context, rawId: Int): Int {
        try {
            val uri = Uri.parse("android.resource://" + context.packageName + "/" + rawId)
            val mediaPlayer = MediaPlayer()
            mediaPlayer.setDataSource(context, uri)
            mediaPlayer.setAudioAttributes(
                AudioAttributes.Builder()
                    .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                    .build()
            )
            mediaPlayer.prepare()
            return mediaPlayer.duration
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return 0
    }
}